<template>
  <view class="seckill-container">
    <scroll-view
      class="content-scroll"
      scroll-y
      refresher-enabled
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh()"
      @scrolltolower="loadMore()"
    >
      <!-- 标题描述 -->
      <view class="section-header">
        <text class="section-title">限时秒杀优惠券</text>
        <text class="section-desc">限时限量，抢完即止</text>
      </view>

      <!-- 优惠券列表 -->
      <view class="coupon-list" v-if="seckillCoupons.length > 0">
        <view 
          v-for="coupon in seckillCoupons" 
          :key="coupon.id" 
          class="coupon-card"
          :class="[coupon.type === 'fixed' ? 'fixed-bg' : 'percent-bg']"
        >
          <view class="coupon-left">
            <view class="coupon-amount">
              <text v-if="coupon.type === 'fixed'" class="symbol">¥</text>
              <text class="number">{{ coupon.discountAmount || 0 }}</text>
              <text v-if="coupon.type === 'percent'" class="symbol">%</text>
            </view>
            <text class="coupon-condition" v-if="coupon.minAmount">满{{ coupon.minAmount }}元可用</text>
          </view>
          <view class="coupon-right">
            <view class="coupon-info">
              <text class="coupon-name">{{ coupon.name || '优惠券' }}</text>
              <text class="coupon-date">有效期至: {{ formatDate(coupon.endTime) }}</text>
              <text class="coupon-timer" v-if="coupon.id && coupon.seckillEndTime">
                剩余 {{ getCountdownText(coupon.id, coupon.seckillEndTime) }}
              </text>
            </view>
            <view class="coupon-action">
              <button 
                class="grab-btn" 
                :disabled="coupon.receiving" 
                @tap="grabCoupon(coupon)"
                :loading="coupon.receiving"
              >
                {{ coupon.receiving ? '领取中...' : '立即抢购' }}
              </button>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && seckillCoupons.length === 0">
        <image src="/static/empty.png" mode="aspectFit" class="empty-image"></image>
        <text class="empty-text">暂无秒杀优惠券</text>
      </view>

      <!-- 加载状态 -->
      <view v-if="loading && !refreshing" class="loading">加载中...</view>
      <view v-if="!hasMore && seckillCoupons.length > 0" class="no-more">没有更多了</view>
    </scroll-view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from 'vue';
import { onShow, onHide } from '@dcloudio/uni-app';
import { listSeckillCouponUsingGet } from '../../backend/couponController';
import { addUserCouponUsingPost } from '../../backend/userCouponController';
import { tokenStore } from "../../store/tokenStore";
import type { API } from '../../backend/typings';

const tokenStoreInstance = tokenStore();

// 状态管理
const loading = ref(false);
const refreshing = ref(false);
const hasMore = ref(true);
const seckillCoupons = ref<(API.CouponVO & { receiving?: boolean })[]>([]);

// 分页参数
const queryParams = reactive({
  current: 1,
  pageSize: 10
});

// 倒计时数据
const couponCountdowns = ref<Record<number, {
  hours: string;
  minutes: string;
  seconds: string;
}>>({});

// 定时器
let countdownTimer: number;

// 获取秒杀优惠券列表
const fetchSeckillCoupons = async (refresh = false) => {
  if (loading.value && !refresh) return;
  
  if (refresh) {
    queryParams.current = 1;
    hasMore.value = true;
    seckillCoupons.value = [];
  }
  
  if (!hasMore.value) return;
  loading.value = true;
  
  try {
    if (!tokenStoreInstance.getToken) {
      uni.showToast({
        title: '请先登录',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    
    const res = await listSeckillCouponUsingGet({
      current: queryParams.current,
      pageSize: queryParams.pageSize
    });
    
    if (res.code === 0 && res.data) {
      const newCoupons = res.data.records || [];
      
      // 添加领取状态属性
      const couponsWithStatus = newCoupons.map(coupon => ({
        ...coupon,
        receiving: false
      }));
      
      seckillCoupons.value = refresh ? couponsWithStatus : [...seckillCoupons.value, ...couponsWithStatus];
      
      // 判断是否还有更多数据
      hasMore.value = newCoupons.length >= queryParams.pageSize;
      
      // 初始化倒计时
      updateAllCountdowns();
    } else {
      uni.showToast({
        title: res.message || '获取优惠券失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取秒杀优惠券失败:', error);
    uni.showToast({
      title: '网络异常，请稍后再试',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    refreshing.value = false;
    uni.stopPullDownRefresh();
  }
};

// 领取优惠券
const grabCoupon = async (coupon: API.CouponVO & { receiving?: boolean }) => {
  if (!coupon.id) return;
  
  if (!tokenStoreInstance.getToken) {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    return;
  }
  
  // 设置领取中状态
  coupon.receiving = true;
  
  try {
    const res = await addUserCouponUsingPost({
      couponId: coupon.id
    });
    
    if (res.code === 0) {
      uni.showToast({
        title: '领取成功',
        icon: 'success'
      });
      
      // 刷新列表
      fetchSeckillCoupons(true);
    } else {
      uni.showToast({
        title: res.message || '领取失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('领取优惠券失败:', error);
    uni.showToast({
      title: '网络异常，请稍后再试',
      icon: 'none'
    });
  } finally {
    coupon.receiving = false;
  }
};

// 更新所有优惠券的倒计时
const updateAllCountdowns = () => {
  seckillCoupons.value.forEach(coupon => {
    if (coupon.id && coupon.seckillEndTime) {
      updateCountdown(coupon.id, coupon.seckillEndTime);
    }
  });
};

// 更新单个优惠券的倒计时
const updateCountdown = (couponId: number, endTimeString: string) => {
  if (!couponId || !endTimeString) return;
  
  const endTime = new Date(endTimeString).getTime();
  const now = new Date().getTime();
  const diff = endTime - now;
  
  if (diff <= 0) {
    couponCountdowns.value[couponId] = {
      hours: '00',
      minutes: '00',
      seconds: '00'
    };
    return;
  }
  
  const hours = Math.floor(diff / (1000 * 60 * 60)).toString().padStart(2, '0');
  const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60)).toString().padStart(2, '0');
  const seconds = Math.floor((diff % (1000 * 60)) / 1000).toString().padStart(2, '0');
  
  couponCountdowns.value[couponId] = { hours, minutes, seconds };
};

// 获取倒计时文本
const getCountdownText = (couponId?: number, endTimeString?: string) => {
  if (!couponId || !endTimeString) return '00:00:00';
  
  // 如果倒计时数据尚未初始化，先计算一次
  if (!couponCountdowns.value[couponId]) {
    updateCountdown(couponId, endTimeString);
  }
  
  const countdown = couponCountdowns.value[couponId];
  if (!countdown) return '00:00:00';
  
  return `${countdown.hours}:${countdown.minutes}:${countdown.seconds}`;
};

// 启动倒计时计时器
const startCountdown = () => {
  if (countdownTimer) clearInterval(countdownTimer);
  updateAllCountdowns();
  countdownTimer = setInterval(() => {
    updateAllCountdowns();
  }, 1000);
};

// 格式化日期
const formatDate = (dateString?: string) => {
  if (!dateString) return '无限期';
  
  const date = new Date(dateString);
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
};

// 下拉刷新
const onRefresh = async () => {
  refreshing.value = true;
  await fetchSeckillCoupons(true);
};

// 加载更多
const loadMore = () => {
  if (hasMore.value && !loading.value) {
    queryParams.current++;
    fetchSeckillCoupons();
  }
};

// 检查登录状态
const checkLogin = () => {
  const token = uni.getStorageSync('token');
  return !!token;
};

// 页面加载时初始化
onMounted(() => {
  if (checkLogin()) {
    fetchSeckillCoupons(true);
    startCountdown();
  } else {
    uni.showToast({
      title: '请先登录',
      icon: 'none'
    });
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});

// 页面显示时启动倒计时
onShow(() => {
  if (seckillCoupons.value.length > 0) {
    startCountdown();
  }
});

// 页面隐藏时清除倒计时
onHide(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});

// 页面卸载时清理
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
});
</script>

<style scoped>
.seckill-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 30rpx;
}

.content-scroll {
  height: 100vh;
}

.section-header {
  padding: 30rpx 30rpx 20rpx;
  background: linear-gradient(135deg, #ff9f43, #ff5722);
  color: #fff;
}

.section-title {
  font-size: 34rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  display: block;
}

.section-desc {
  font-size: 24rpx;
  opacity: 0.8;
  display: block;
}

.coupon-list {
  padding: 20rpx;
}

.coupon-card {
  display: flex;
  margin-bottom: 30rpx;
  background-color: #fff;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
  overflow: hidden;
  position: relative;
}

.fixed-bg .coupon-left {
  background: linear-gradient(135deg, #ff9f43, #ff5722);
}

.percent-bg .coupon-left {
  background: linear-gradient(135deg, #4facfe, #00f2fe);
}

.coupon-left {
  width: 220rpx;
  height: 180rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: white;
  position: relative;
}

.coupon-left:after {
  content: '';
  position: absolute;
  right: 0;
  top: 10%;
  height: 80%;
  width: 2rpx;
  background: rgba(255,255,255,0.3);
}

.coupon-right {
  flex: 1;
  display: flex;
  padding: 20rpx;
  justify-content: space-between;
  align-items: center;
}

.coupon-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.coupon-amount {
  display: flex;
  align-items: baseline;
  justify-content: center;
}

.symbol {
  font-size: 30rpx;
}

.number {
  font-size: 60rpx;
  font-weight: bold;
  margin: 0 4rpx;
}

.coupon-condition {
  font-size: 22rpx;
  color: rgba(255,255,255,0.9);
  text-align: center;
  margin-top: 8rpx;
  background-color: rgba(0,0,0,0.1);
  padding: 2rpx 12rpx;
  border-radius: 12rpx;
}

.coupon-name {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 8rpx;
  display: block;
}

.coupon-date {
  font-size: 24rpx;
  color: #999;
  display: block;
  margin-bottom: 10rpx;
}

.coupon-timer {
  font-size: 24rpx;
  color: #ff5722;
  background-color: rgba(255, 87, 34, 0.1);
  padding: 4rpx 12rpx;
  border-radius: 20rpx;
  display: inline-block;
}

.coupon-action {
  margin-left: 20rpx;
}

.grab-btn {
  background: linear-gradient(135deg, #ff9800, #ff5722);
  color: #fff;
  font-size: 26rpx;
  height: 70rpx;
  border-radius: 35rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0 30rpx;
  border: none;
  min-width: 160rpx;
}

.grab-btn:active {
  transform: scale(0.98);
  opacity: 0.9;
}

.grab-btn[disabled] {
  background: #cccccc;
  opacity: 0.8;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 100rpx 30rpx;
}

.empty-image {
  width: 200rpx;
  height: 200rpx;
  margin-bottom: 20rpx;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}

.loading, .no-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 24rpx;
}
</style> 